<template>
  <div class="fm-uplaod-container" :id="uploadId">
    <!-- <draggable
      class="drag-img-list"
      v-model="fileList"
      v-bind="{ group: uploadId, ghostClass: 'ghost', animation: 200 }"
      :no-transition-on-drag="true"
    >
        </draggable> -->
    <div class="file_list">
      <div
        v-for="(item, fileIndex) in fileList"
        :key="item.key"
        :style="{ width: width + 'px', height: height + 'px' }"
        :class="{
          uploading: item.status == 'uploading',
          'is-success': item.status == 'success',
          'is-diabled': disabled,
        }"
        class="upload-file"
      >
        <div class="file_content">
          <file-component
            ref="fileComponent"
            :uri="item.uri"
            :fileUrl="item.fileUrl"
            :fileType="item.fileType"
            :fileId="item.fileId"
            :remote="remote"
          />
        </div>
        <el-progress
          v-if="item.status == 'uploading'"
          :width="miniWidth * 0.9"
          class="upload-progress"
          type="circle"
          :percentage="item.percent"
        />

        <div class="uplaod-action" :style="{ height: miniWidth / 4 + 'px' }">
          <i
            class="iconfont icon-tupianyulan"
            :title="$t('fm.upload.preview')"
            @click="handlePreviewFile(fileIndex)"
            :style="{ 'font-size': miniWidth / 8 + 'px' }"
          ></i>
          <i
            v-if="isEdit"
            class="iconfont icon-sync1"
            :title="$t('fm.upload.edit')"
            @click="handleEdit(item.key)"
            :style="{ 'font-size': miniWidth / 8 + 'px' }"
          ></i>
          <i
            v-if="isDelete && fileList.length > min"
            class="iconfont icon-delete"
            :title="$t('fm.upload.delete')"
            @click="handleRemove(item.key)"
            :style="{ 'font-size': miniWidth / 8 + 'px' }"
          ></i>
        </div>
      </div>
    </div>

    <el-upload
      ref="uploadFiledInput"
      v-show="!disabled"
      action="#"
      list-type="fileList"
      :limit="length"
      :auto-upload="true"
      :accept="validRule"
      :multiple="multiple"
      :headers="getHeaders()"
      :on-exceed="onExceedAction"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
      :style="{ width: 400 + 'px', height: height + 'px' }"
      :show-file-list="false"
    >
      <el-button
        :loading="loading"
        type="text"
        size="medium"
        @click="editIndex = -1"
      >
        点击上传
      </el-button>
      <!-- <i
        class="el-icon-plus"
        @click.self="handleAdd"
        :style="{
          fontSize: miniWidth / 4 + 'px',
          marginTop: -miniWidth / 8 + 'px',
          marginLeft: -miniWidth / 8 + 'px',
        }"
      ></i> -->
      <div slot="tip" class="el-upload__tip">{{ promptString }}</div>
    </el-upload>
  </div>
</template>

<script>
// import Viewer from 'viewerjs'
import Draggable from 'vuedraggable'
import FileComponent from './fileComponent.vue'
require('viewerjs/dist/viewer.css')

export default {
  components: {
    Draggable,
    FileComponent,
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    width: {
      type: Number,
      default: 100,
    },
    height: {
      type: Number,
      default: 100,
    },
    token: {
      type: String,
      default: '',
    },
    domain: {
      type: String,
      default: '',
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    length: {
      type: Number,
      default: 9,
    },
    isDelete: {
      type: Boolean,
      default: false,
    },
    min: {
      type: Number,
      default: 0,
    },
    meitu: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    remote: {
      type: Object,
      default: () => ({}),
    },
    type: {
      type: Array,
      default: () => [],
    },
    size: {
      type: Number,
    },
  },
  data() {
    return {
      fileList: this.value.map((item) => {
        return {
          key: item.key
            ? item.key
            : new Date().getTime() + '_' + Math.ceil(Math.random() * 99999),
          fileUrl: item.fileUrl,
          uri: item.uri,
          fileId: item.fileId ? item.fileId : '',
          percent: item.percent ? item.percent : 100,
          status: item.status ? item.status : 'success',
        }
      }),
      viewer: null,
      uploadId: 'upload_' + new Date().getTime(),
      editIndex: -1,
      meituIndex: -1,
      loading: false,
    }
  },
  computed: {
    miniWidth() {
      if (this.width > this.height) {
        return this.height
      } else {
        return this.width
      }
    },
    validRule() {
      if (this.type && this.type.length) {
        return this.type.map((item) => `.${item}`).join(',')
      }
      return 'file'
    },
    promptString() {
      let fileTypeStr = ''
      if (this.type && this.type.length) {
        fileTypeStr =
          '文件格式仅限' + this.type.map((item) => `.${item}`).join(',')
      }
      if (this.size) {
        let bitStr = `${this.size}KB`
        fileTypeStr =
          fileTypeStr === ''
            ? `文件大小限制 ${bitStr} 内`
            : `${fileTypeStr}, 小于 ${bitStr}`
      }
      return fileTypeStr
    },
  },
  created() {},
  mounted() {
    console.log('upload mounted')
    console.log(this)
    console.log(this.fileList)
    // this.$emit('input', this.fileList)
  },
  methods: {
    beforeUpload(file) {
      const { size, type } = file
      if (this.remote['uploadBeforeUpload']) {
        return this.remote['uploadBeforeUpload'](file)
      }
      let isLimitType =
        this.type.findIndex((item) => item === type.split('/')[1]) !== -1
      let isLtSize = this.size * 1024 >= size
      if (!isLimitType) {
        this.$message({ type: 'error', message: '请上传指定格式文件' })
      }
      if (!isLtSize) {
        this.$message({ type: 'error', message: '超过文件大小限制' })
      }

      return isLimitType && isLtSize
    },
    beforeRemove(file, fileList) {
      if (this.remote['UploadBeforeRemove']) {
        return this.remote['UploadBeforeRemove'](file, fileList)
      }
      return true
    },
    httpRequest(file) {
      if (!file) return
      const lastPlaceIndex = this.fileList.length
      const nameSplitArr = file.file.name.split('.')
      const fileType = nameSplitArr[nameSplitArr.length - 1]
      const reader = new FileReader()
      debugger
      if (
        fileType === 'png' ||
        fileType === 'jpg' ||
        fileType === 'jpeg' ||
        fileType === 'gif'
      ) {
        const _this = this
        reader.onload = function (e) {
          let base64Str = e.target.result
          if (_this.editIndex >= 0) {
            _this.$set(_this.fileList, _this.editIndex, {
              key:
                new Date().getTime() + '_' + Math.ceil(Math.random() * 99999),
              status: 'uploading',
              percent: 0,
              fileUrl: base64Str,
              fileType,
            })
            _this.editIndex = -1
          } else {
            _this.fileList.push({
              key:
                new Date().getTime() + '_' + Math.ceil(Math.random() * 99999),
              status: 'uploading',
              percent: 0,
              fileUrl: base64Str,
              fileType,
            })
          }
          _this.$emit('input', _this.fileList)
        }
        reader.readAsDataURL(file.file)
      } else {
        if (this.editIndex >= 0) {
          this.$set(this.fileList, this.editIndex, {
            key: new Date().getTime() + '_' + Math.ceil(Math.random() * 99999),
            status: 'uploading',
            percent: 0,
            fileUrl: '/',
            fileType,
          })
          this.editIndex = -1
        } else {
          this.fileList.push({
            key: new Date().getTime() + '_' + Math.ceil(Math.random() * 99999),
            status: 'uploading',
            percent: 0,
            fileUrl: '/',
            fileType,
          })
        }
        this.$emit('input', this.fileList)
      }
      this.$refs.uploadFiledInput.clearFiles()
      if (this.remote['uploadHttpRequest']) {
        this.remote['uploadHttpRequest'](file)
          .then((res) => {
            const index = lastPlaceIndex
            this.$set(this.fileList, index, {
              ...res,
              percent: 100,
              status: 'success',
              key:
                new Date().getTime() + '_' + Math.ceil(Math.random() * 99999),
            })

            this.$emit('input', this.fileList)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    onExceedAction() {
      this.$message.warning('超过最大上传限制')
    },
    getHeaders() {
      if (this.remote['getUploadHeaders']) {
        return this.remote['getUploadHeaders']()
      }
      return {}
    },
    handlePreviewFile(index) {
      // console.log(this.$children)
      // console.log(index)
      console.log(this.$refs.fileComponent[index])
      this.$refs.fileComponent[index].handlePreview()
    },
    handleEdit(key) {
      this.editIndex = this.fileList.findIndex((item) => item.key === key)
      console.log(this.$refs.uploadFiledInput)
      this.$refs.uploadFiledInput.$refs['upload-inner'].handleClick()
    },
    handleRemove(key) {
      this.fileList.splice(
        this.fileList.findIndex((item) => item.key === key),
        1
      )
    },
  },
  watch: {
    fileList: {
      deep: true,
      handler(val) {
        this.$emit('input', this.fileList)
      },
    },
    value: {
      deep: true,
      handler: function (val, oldVal) {
        console.log('watch upload value change')
        console.log(val)
      },
    },
  },
}
</script>

<style lang="scss">
.fm-uplaod-container {
  .is-disabled {
    position: relative;

    &::after {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      // background: rgba(0,0,0,.1);
      content: '';
      display: block;
      cursor: not-allowed;
    }
  }

  .upload-file {
    margin: 0 10px 10px 0;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    // background: #fff;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    position: relative;
    vertical-align: top;
    &:hover {
      .uplaod-action {
        display: flex;
      }
    }
    .uplaod-action {
      position: absolute;
      // top: 0;
      // height: 30px;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.6);
      display: none;
      justify-content: center;
      align-items: center;
      i {
        color: #fff;
        cursor: pointer;
        margin: 0 5px;
      }
    }
    &.is-success {
      .item-status {
        position: absolute;
        right: -15px;
        top: -6px;
        width: 40px;
        height: 24px;
        background: #13ce66;
        text-align: center;
        transform: rotate(45deg);
        box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
        & > i {
          font-size: 12px;
          margin-top: 11px;
          color: #fff;
          transform: rotate(-45deg);
        }
      }
    }
    &.uploading {
      &:before {
        display: block;
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.3);
      }
    }
    .upload-progress {
      position: absolute;
      .el-progress__text {
        color: #fff;
        font-size: 16px !important;
      }
    }
    img {
      max-width: 100%;
      max-height: 100%;
      vertical-align: middle;
    }
  }
  .el-upload--picture-card {
    position: relative;
    overflow: hidden;
    .el-icon-plus {
      position: absolute;
      top: 50%;
      left: 50%;
    }
  }
  .upload-input {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: block;
    opacity: 0;
    cursor: pointer;
  }

  .drag-img-list {
    display: inline;

    .ghost {
      position: relative;
      &::after {
        width: 100%;
        height: 100%;
        display: block;
        content: '';
        background: #fbfdff;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        border: 1px dashed #3bb3c2;
      }
    }

    & > div {
      cursor: move;
    }
  }
  .upload-file-img {
    width: 100px;
    height: 100px;
  }
  .uploadHttpRequest {
    width: 100%;
    height: 100%;
  }
  .file_content {
    width: 100%;
    height: 100%;
  }
}

.viewer-container {
  z-index: 9999 !important;
}
.media_wrap {
  width: 120px;
  height: 120px;
}
.fm_upload_field {
  position: relative;
}
</style>
